package com.item.action;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.Page;
import com.base.dialect.PaginationSupport;
import com.base.support.PropertySupport;
import com.base.util.JSONUtils;
import com.item.dao.model.PassToken;
import com.item.dao.model.User;
import com.item.dao.model.UserExample;
import com.item.exception.ActionException;
import com.item.exception.JSONRepUtils;
import com.item.exception.MErrorEnum;
import com.item.filter.LoginFilter;
import com.item.service.PassTokenService;
import com.item.service.UserService;
import com.item.util.SimpleMailSender;

@Controller
public class UserController extends CoreController {
	@Autowired
	private UserService userService;
	
	@Autowired
	private PassTokenService tokenService;
	private static String passFormat = PropertySupport.getProperty("pass.format");
	private static String url = PropertySupport.getProperty("pass.url");
	
	@RequestMapping("/Mlogin")
	@ResponseBody
	public String login(User user, HttpSession session) throws Exception {
		//分为通过用户名密码登陆和QQ登陆
		String message = "";
		UserExample example = new UserExample();
		List<User> list = null;
		if(StringUtils.isNotBlank(user.getUsername()) && StringUtils.isNotBlank(user.getPassword())){
			example.createCriteria().andUsernameEqualTo(user.getUsername()).andPasswordEqualTo(user.getPassword());
			UserExample.Criteria creatia1 = example.createCriteria().andMailEqualTo(user.getUsername()).andPasswordEqualTo(user.getPassword());
			example.or(creatia1);
		}else if(StringUtils.isNotBlank(user.getQqNumber())){
			example.createCriteria().andQqNumberEqualTo(user.getQqNumber());
		}else{
			if(StringUtils.isBlank(user.getMail())) {
				throw new ActionException("info");
			}
		}
		list = userService.selectByExample(example);
		if(list.size() > 0) {
			user = list.get(0);
			Map<String, String> map = new HashMap<String, String>();
			map.put("id", user.getId());
			session.setAttribute("userid", user.getId());
			session.setAttribute("account", user.getUsername());
			session.setAttribute("isM", 1);
			session.setAttribute(LoginFilter.SESSION_USER_KEY, map);
			message = JSONRepUtils.serialize(user, 1);
		} else {
			throw new ActionException(MErrorEnum.LOGIN_FAIL_ERROR);
		}
		
		return message;
	}
	
	
	
	@RequestMapping("/MLogout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:webindex.do";
	}
	
	@RequestMapping("/MChangePass")
	@ResponseBody
	public String changepass(HttpSession session,User user, String passsordNew, Integer isM)throws Exception {
		UserExample uex = new UserExample();
		uex.createCriteria().andIdEqualTo(user.getId()).andPasswordEqualTo(user.getPassword());
		List<User> users = userService.selectByExample(uex);
		if(users == null || users.size() < 1){
			throw new ActionException(MErrorEnum.PASSWORD_ERROR);
		}
		user.setPassword(passsordNew);
		userService.updateByPrimaryKeySelective(user);
		String message = JSONRepUtils.serialize("success", isM);
		return message;
	}
	
	@RequestMapping("/MPassMail")
	@ResponseBody
	public String passmail(HttpSession session,User user, Integer isM)throws Exception {
		if(StringUtils.isBlank(user.getMail())) {
			throw new ActionException("mail");
		}
		UserExample uex = new UserExample();
		uex.createCriteria().andMailEqualTo(user.getMail());
		List<User> users = userService.selectByExample(uex);
		if(users == null || users.size() < 1){
			throw new ActionException(MErrorEnum.EMAIL_NOT_EXIST);
		}
		User u = users.get(0);
		//向token表中插入一条记录
		PassToken token = new PassToken();
		token.setUserid(u.getId());
		token.setCreateTime(new Date());
		tokenService.insert(token);
		StringBuilder sb = new StringBuilder();
		sb.append(url).append("token=").append(token.getId());
		String content = String.format(passFormat, sb.toString(),sb.toString());
//		System.out.println(content);
		SimpleMailSender sender = new SimpleMailSender(PropertySupport.getProperty("mail.username"), PropertySupport.getProperty("mail.password"));
		if(!sender.send(u.getMail(), "教材吧密码找回", content)){
			throw new ActionException(MErrorEnum.EMAIL_SEND_ERROR);
		}
		String message = JSONRepUtils.serialize("success", isM);
		return message;
	}
	
	@RequestMapping("/passTokenCheck")
	@ResponseBody
	public String PassTokenCheck(HttpSession session,String token, Integer isM)throws Exception {
		String message = "";
		if(StringUtils.isBlank(token)) {
			throw new ActionException("token");
		}
		PassToken t = tokenService.selectByPrimaryKey(token);
		Date now = new Date();
//		System.out.println(now.getTime() - t.getCreateTime().getTime());
		if(t== null || now.getTime() - t.getCreateTime().getTime() > 24 * 3600 * 1000){
			message = JSONRepUtils.serialize("outoftime", isM);
			return message;
		}
		User user = userService.selectByPrimaryKey(t.getUserid());
		message = JSONRepUtils.serialize(user.getId(), isM);
		return message;
	}
	
	@RequestMapping("/passReset")
	@ResponseBody
	public String passReset(HttpSession session,User user, Integer isM)throws Exception {
		String message = "";
//		System.out.println(user.getId());
		int rows = userService.updateByPrimaryKeySelective(user);
		if(rows < 1){
			throw new ActionException(MErrorEnum.USER_UPDATE_ERROR);
		}else{
			message = JSONRepUtils.serialize("success", isM);
		}
		return message;
	}
	
	
	/**
	 * 注册、更新用户信息、修改密码
	 * @param user
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveUser")
	@ResponseBody
	public String register(User user, Integer isM, HttpSession session) throws Exception {
		String message = "";
		
		if(StringUtils.isBlank(user.getId())) { //注册
			if(StringUtils.isBlank(user.getUsername())) {
				throw new ActionException("username");
			}
			if(StringUtils.isBlank(user.getPassword())) {
				throw new ActionException("password");
			}
			
			UserExample userExample = new UserExample();
			userExample.createCriteria().andUsernameEqualTo(user.getUsername());
			UserExample.Criteria cr1 = userExample.createCriteria().andMailEqualTo(user.getMail());
			userExample.or(cr1);
			if(userService.countByExample(userExample) == 0) {
				user.setCreateTime(new Date()); //创建时间
				int rows = userService.insertSelective(user);
				if(rows > 0) {
					message = JSONRepUtils.serialize(user, isM);
				} else {
					throw new ActionException(MErrorEnum.USER_INSERT_ERROR);
				}
			} else {//用户名已存在
				throw new ActionException(MErrorEnum.USER_EXISTS);
			}
		} else { //修改
			user.setModifyTime(new Date()); //修改时间
			int rows = userService.updateByPrimaryKeySelective(user);
			if(rows > 0) {
				message = JSONRepUtils.serialize(user, isM);
			} else {
				throw new ActionException(MErrorEnum.USER_INSERT_ERROR);
			}
		}
		
		return message;
	}
	
	@RequestMapping(value="/findByIdUser")
	@ResponseBody
	public String findByIdUser(String id,HttpSession session)throws Exception{		
		User n = userService.selectByPrimaryKey(id);
		return JSONUtils.serialize(n);
	}
	
	@RequestMapping(value="/findByQQUser")
	@ResponseBody
	public String findByQQUser(String qq,HttpSession session)throws Exception{		
//		System.out.println(qq);
		UserExample uex = new UserExample();
		uex.createCriteria().andQqNumberEqualTo(qq);
		List<User> users = userService.selectByExample(uex);
		User user = null;
		if(users != null && users.size() > 0){
			user = users.get(0);
		}else{
			user = new User();
			user.setCreateTime(new Date());
			user.setUsername("");
			user.setAddress("");
			user.setsName("");
			user.setDmName("");
			user.setMjName("");
			user.setMail("");
			user.setQqNumber(qq);
			userService.insert(user);
		}
//		System.out.println(JSONUtils.serialize(user));
		return JSONUtils.serialize(user);
	}
	
	@RequestMapping("/listUser")
	@ResponseBody
	public String list(Page param, User user, Integer isNotPage, Integer isM) throws Exception{
		Object objForSer = null;
		UserExample example = new UserExample();
		UserExample.Criteria criteria = example.createCriteria();
		PaginationSupport.setContext(param.getPageStart(), param.getPageSize(), null);

		if(StringUtils.isNotBlank(user.getDmName())) {
			criteria.andDmNameLike("%" + user.getDmName() + "%");
		}
		
		List<User> list = userService.selectByExample(example);
		if(isNotPage != null && isNotPage == 1) {
			objForSer = list;
		} else {
			objForSer = new Page(PaginationSupport.getContext().getTotalCount(), list);
		}
		return JSONRepUtils.serialize(objForSer, isM);
	}
	
	@RequestMapping("/showlistUser")
	public String list() {
		return "user/userList";
	}
	
	@RequestMapping("/toEditUser")
	public String toEdit()throws Exception{
		return "user/userEdit";
	}
	
	@RequestMapping("/delUser")
	@ResponseBody
	public String del(String id,String url,HttpSession session)throws Exception{
		String[] ids = id.split(",");
		int len = ids.length;
		for(int i = 0; i < len; i++) {
			userService.deleteByPrimaryKey(ids[i]);
		}
		return "{\"success\":true}";
	}
	
	
	
	 
}
